package main

import (
	"flag"
	"gitee.com/yysf_xin/dplog/pkg/ck"
	"gitee.com/yysf_xin/dplog/pkg/config"
	"gitee.com/yysf_xin/dplog/pkg/extracter/fex"
	"gitee.com/yysf_xin/dplog/pkg/extracter/java"
	"gitee.com/yysf_xin/dplog/pkg/slog"
	"io/fs"
	"path/filepath"
	"strings"
	"time"
)

type Option struct {
	Dir     string
	Date    string
	ck      ck.Option
	java    java.Opt
	log     slog.Option
	mybatis StringFlags
}

type StringFlags []string

func (i *StringFlags) String() string {
	return "mybatis package name"
}

func (i *StringFlags) Set(value string) error {
	*i = append(*i, value)
	return nil
}

type uploadApp struct {
	opt      Option
	em1      *ck.Collect
	err      error
	mk       *fex.MakeLog
	c        *slog.Collect
	allStart time.Time
	total    uint
}

var app uploadApp

func main() {
	flag.StringVar(&app.opt.Dir, "dir", "", "use log dir")
	flag.StringVar(&app.opt.Date, "date", "", "upload log date")
	java.InitFlag(&app.opt.java)
	flag.Var(&app.opt.mybatis, "mybatis", "mybatis packages")
	slog.InitFlag(&app.opt.log)
	ck.InitFlag(&app.opt.ck, "ck_")
	flag.Parse()

	app.mk = fex.NewMakeLog(&app.opt.java, "")
	app.allStart = time.Now()

	if app.opt.Dir == "" {
		println("dir is empty")
		return
	}
	if app.opt.Date == "yest" {
		app.opt.Date = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	}
	root := filepath.Join(app.opt.Dir, app.opt.Date)
	println("begin upload from", root)

	var err error
	if app.opt.ck.Db != "" {
		app.em1, err = ck.NewCollect(&app.opt.ck)
		if err != nil {
			panic(err)
		}
		// []string{"org.apache.ibatis.logging.jdbc.BaseJdbcLogger", "dao."}
		app.c = slog.NewCollect(&app.opt.log, app.mk, java.NewMybatis(app.em1, app.opt.mybatis))
	}

	if strings.HasSuffix(root, ".log.gz") {
		err = startUpload(root, filepath.Base(root))
	} else {
		err = filepath.Walk(root, func(path string, info fs.FileInfo, err error) error {
			if info == nil {
				return nil
			}
			if strings.HasSuffix(info.Name(), ".log.gz") {
				err = startUpload(path, info.Name())
			}
			return nil
		})
	}

	if app.em1 != nil {
		app.em1.Flush()
	}
	if app.c != nil {
		err = app.c.Close()
	}
	println("总耗时", time.Now().Sub(app.allStart).String(), "总共数据量", app.total)

}

func startUpload(path, name string) (err error) {
	app.mk.Name = name
	hostDir := filepath.Dir(path)
	host := filepath.Base(hostDir)
	service := filepath.Base(filepath.Dir(hostDir))
	config.Ip = host
	println("开始上传", service, host, app.mk.Name)
	if app.c != nil {
		var meta slog.MetaData
		meta.Ip = host
		app.c.Init(&meta)
		var r *slog.FileReader
		r, err = slog.NewFileReader(path, app.c)
		if err != nil {
			println("read file error", err.Error())
			return nil
		}
		start := time.Now()
		r.Run()
		app.c.Flush()
		app.em1.Flush()
		_ = r.Close()
		println("耗时", time.Now().Sub(start).String(), "当前数据量", app.em1.Total)
		app.total += app.em1.Total
		app.em1.Total = 0
	}
	return nil
}
